package cn.lf.android.lawfirm.uploadcontroller.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import cn.lf.android.lawfirm.AppConfig;
import cn.lf.android.lawfirm.MyApplication;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.downloadcontroller.modle.Agreement;
import cn.lf.android.lawfirm.http.download.DownloadUtil;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.worklog.AddWorkLogActivity;
import cn.lf.android.lawfirm.worklog.WorkLogActivity;

import static cn.lf.android.lawfirm.Constants.file;
import static cn.lf.android.lawfirm.R.id.wait;

public class UpAgreementAdapter extends BaseAdapter {
    private List<Agreement> list;
    private LayoutInflater inflater;
    private Activity context;
    private final static int DOWNLOADSUCCESS = 1;
    private final static int DOWNLOADFAIL = 2;
    private final static int DOWNLOAD = 0;
    private boolean isSuccess = false;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADSUCCESS://成功
                    isSuccess = true;
                    list.get(download_position).load_status = "2";
                    notifyDataSetChanged();
                    Toast.makeText(context, "下载完成", Toast.LENGTH_LONG).show();
                    Bundle bundle = msg.getData();
//                    File file = new File(bundle.getString("path"));
//                    File to = new File(makeDirsPath(), "我就不信了.docx");
//                    file.renameTo(to);
                    chageFileName(bundle.getString("path"), list.get(bundle.getInt("position")).LsysFileName);
                case DOWNLOADFAIL://失败
                    isSuccess = false;
                    list.get(download_position).load_status = "3";
                    notifyDataSetChanged();
                case DOWNLOAD://进行中
                    if (null != msg.obj) {
                        int i = (int) msg.obj;
                        DebugLog.e("进行中==" + i);
                        if (i < 100) {
                            list.get(download_position).load_status = "1";
                            notifyDataSetChanged();
                        }
                    }
            }
        }

    };
    /**
     * 当前下载位置
     **/
    private int download_position = -1;
    private Animation operatingAnim;
    private String mFrom = "";

    public UpAgreementAdapter(Activity context, List<Agreement> list, String from) {
        this.context = context;
        this.list = list;
        this.inflater = LayoutInflater.from(context);
        this.mFrom = from;
        operatingAnim = AnimationUtils.loadAnimation(context, R.anim.rotate);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
//        ViewHolder holder;
//        if (convertView == null) {
//            holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.item_agreement_upload, null);
        TextView names = (TextView) convertView
                .findViewById(R.id.name);
        TextView delete = (TextView) convertView
                .findViewById(R.id.delete);
        final TextView tv_url = (TextView) convertView
                .findViewById(R.id.url);
        final TextView tv_wait = (TextView) convertView.findViewById(wait);
//            convertView.setTag(holder);
//        } else {
//            holder = (ViewHolder) convertView.getTag();
//        }
        final Agreement bean = list.get(position);

        names.setText(bean.fileName);
        if (null == bean.fileName || bean.fileName.length() == 0) {//合同字段空
            names.setText(bean.LsysFileName);//用日志字段
        }
        if ("日志编辑".equals(mFrom) || "承办申请".equals(mFrom) || "工作日志添加".equals(mFrom)) {
            tv_url.setVisibility(View.GONE);
            delete.setVisibility(View.VISIBLE);
        } else {//日志审批
            delete.setVisibility(View.GONE);
            tv_url.setVisibility(View.VISIBLE);
            if (bean.load_status.equals("0")) {//下载状态  0-未开始 1-进行中 2-成功 3-失败
                tv_url.setVisibility(View.VISIBLE);
                tv_wait.setVisibility(View.GONE);
                operatingAnim.cancel();
            } else if (bean.load_status.equals("1")) {
                tv_url.setVisibility(View.GONE);
                tv_wait.setVisibility(View.VISIBLE);
                tv_wait.setAnimation(operatingAnim);
                operatingAnim.start();
            } else if (bean.load_status.equals("2")) {
                tv_url.setVisibility(View.GONE);
                tv_wait.setVisibility(View.GONE);
                operatingAnim.cancel();
            } else if (bean.load_status.equals("3")) {
                tv_url.setVisibility(View.VISIBLE);
                tv_wait.setVisibility(View.GONE);
                operatingAnim.cancel();
            }
        }
//        if ("日志审批".equals(mFrom)) {
//            tv_url.setVisibility(View.VISIBLE);
//        } else {
//            tv_url.setVisibility(View.GONE);
//        }
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//bean.filepath
                if ("日志编辑".equals(mFrom)) {
                    if (null != bean.localpath && bean.localpath.length() > 0) {
                        ((WorkLogActivity) context).doDelete(position);
                    } else {
                        ((WorkLogActivity) context).doDelete(position, bean.GUID);
                    }
                } else if ("工作日志添加".equals(mFrom)) {
                    ((AddWorkLogActivity) context).doDelete(position);
                } else if ("承办申请".equals(mFrom)) {
                    list.remove(position);
                    notifyDataSetChanged();
                }
            }
        });
        tv_url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//bean.filepath
                DebugLog.e("1111111bean.filepath==" + bean.filepath);
                makeDirs();
                final File file = new File(MyApplication.getInstance().getFilePath(), getNameFromUrl(bean.filepath));
                // 创建文件
                try {
                    file.createNewFile();
                } catch (Exception e) {
                    DebugLog.e("创建失败");
                }
                if (cacheDir.exists()) {
                    download_position = position;
                    download(position, bean.filepath, file);
                } else {
                    download_position = position;
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            download(position, bean.filepath, file);
                        }
                    }, 1000);
                }

            }
        });
        return convertView;
    }

//    class ViewHolder {
//        TextView names, url,wait;
//    }

    File cacheDir;

    private void makeDirs() {
        String CACHE_DIR;
        String DirFileName = "lawfirm";
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {//
            Log.e("SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getExternalStorageDirectory() + "/"
                    + DirFileName;
        } else {
            Log.e("非SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getRootDirectory().getAbsolutePath() + "/"
                    + DirFileName;
        }
        cacheDir = new File(CACHE_DIR);
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    private String makeDirsPath() {
        String CACHE_DIR;
        String DirFileName = "lawfirm";
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {//
            Log.e("SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getExternalStorageDirectory() + "/"
                    + DirFileName;
        } else {
            Log.e("非SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getRootDirectory().getAbsolutePath() + "/"
                    + DirFileName;
        }
        return CACHE_DIR;
    }

    private void download(final int position, String url, File file) {
        DownloadUtil.get().download(AppConfig.URL_DOWN + url, file, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(String path) {
                Message msg = new Message();
                msg.what = UpAgreementAdapter.DOWNLOADSUCCESS;
                Bundle bundle = new Bundle();
                bundle.putString("path", path);//bundle中也可以放序列化或包裹化的类对象数据
                bundle.putInt("position", position);
                msg.setData(bundle);
                mHandler.sendMessage(msg);
                DebugLog.e("下载完成==" + path);
            }

            @Override
            public void onDownloading(int progress) {
                Message msg = new Message();
                msg.what = UpAgreementAdapter.DOWNLOAD;
                msg.obj = progress;
                mHandler.sendMessage(msg);
                DebugLog.e("777" + progress);
            }

            @Override
            public void onDownloadFailed() {
                Message msg = new Message();
                msg.what = UpAgreementAdapter.DOWNLOADFAIL;
                mHandler.sendMessage(msg);
                DebugLog.e("下载失败");
            }
        });
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    private void chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        //前面路径必须一样才能修改成功
        String path = filePath.substring(0, filePath.lastIndexOf("/") + 1) + reName;
        File newFile = new File(path);
        file.renameTo(newFile);
//        copy(filePath, makeDirsPath());
    }
}
